package com.rose;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.LinkedList;
import java.util.Properties;

public class ChatService
{
	private static ChatService cs;
	private Properties userList;
	private LinkedList<String> chatMsg;
	public ChatService(Properties userList, LinkedList<String> chatMsg)
	{
		super();
		this.userList = userList;
		this.chatMsg = chatMsg;
	}
	
	private ChatService()
	{
		
	}
	public static ChatService instance()
	{
		if(null == cs)
		{
			cs = new ChatService();
		}
		return cs;
		
	}
	private Properties loadUser() throws IOException
	{
		if(null == userList)
		{
			File f = new File("userFile.properties");
			if(!f.exists())
			{
				f.createNewFile();
			}
			userList = new Properties();
			userList.load(new FileInputStream(f));
		}
		return userList;
	}
	
	private boolean saveUserList() throws IOException
	{
		if(null == userList)
		{
			return false;
		}
		userList.store(new FileOutputStream("userFile.properties"), "userList");
		return true;
	}
	
	public boolean vaildLogin(String user, String pass) throws IOException
	{
		/*if(null == loadUser().getProperty(user))
		{
			return false;
		}*/
		if(loadUser().getProperty(user).equals(pass))
		{
			return true;
		}
		return false;
	}
	
	public boolean addUser(String name, String pass) throws Exception
	{
		if(null == userList)
		{
			userList = loadUser();
		}
		if(userList.contains(name))
		{
			
		}
		
		userList.setProperty(name, pass);
		saveUserList();
		return true;
	}
	
	public String getMsg()
	{
		if(null == chatMsg)
		{
			chatMsg = new LinkedList<String>();
			return "";
		}
		String result = "";
		for(String tmp: chatMsg)
		{
			result += tmp + "\n";
		}
		
		return result;
	}
	
	public void addMsg(String user, String msg)
	{
		if(null == chatMsg)
		{
			chatMsg = new LinkedList<String>();
		}
		if(chatMsg.size() > 40)
		{
			chatMsg.removeFirst();
		}
	}
	
	
}
